package com.conghu.crm.settings.service.impl;

import com.conghu.crm.exception.LoginException;
import com.conghu.crm.settings.dao.UserDao;
import com.conghu.crm.settings.domain.User;
import com.conghu.crm.settings.service.UserService;
import com.conghu.crm.utils.DateTimeUtil;
import com.conghu.crm.utils.SqlSessionUtil;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class UserServiceImpl implements UserService {

    //服务对象内部使用Dao处理底层数据库
    private UserDao userDao = SqlSessionUtil.getSqlSession().getMapper(UserDao.class);

    /**
     * 业务：登录处理
     * @param loginAct
     * @param loginPwd
     * @param userIp
     * @return
     * @throws LoginException
     */
    @Override
    public User login(String loginAct, String loginPwd, String userIp) throws LoginException {
        Map<String, String> map = new HashMap<>();
        map.put("loginAct", loginAct);
        map.put("loginPwd", loginPwd);

        //调用dao对象查询
        User user = userDao.login(map);

        if(user == null){
            throw new LoginException("账号或密码错误");
        }

        String expireTime = user.getExpireTime();
        if(expireTime.compareTo(DateTimeUtil.getSysTime()) < 0){
            throw new LoginException("账号已失效");
        }

        String lockState = user.getLockState();
        if(lockState.equals("0")){
            throw new LoginException("账号被锁定");
        }

        String allowIps = user.getAllowIps();
        if(!allowIps.contains(userIp)){
            throw new LoginException("拒绝本IP的访问");
        }

        return user;
    }

    /**
     * 业务：查询所有的用户
     * @return
     */
    @Override
    public List<User> getUserList() {
        List<User> userList = userDao.selectAll();
        return userList;
    }
}
